import { getIsDescendingOrder, setIsDescendingOrder, sortSgbList } from "@/utils/utils";
import { getSgbItem, getShiJiType, getShiJiList, getAllShiJiList } from "../../api/cloudbase-sgbedit";
import { gedanController } from "../../api/cloudbase-user-action-log";
import { shallowReactive } from "vue";
import { GEDAN_LIST_TYPE } from "@/utils/constant";
const state = {
  list: [],
  type: [],
  navList: [],
  allSgbDbList: [],
  isDescendingOrder: getIsDescendingOrder(),
};

const getters = {
  isDescendingOrder: (state) => state.isDescendingOrder,
  getNavList: (state) => state.getNavList,
};
const mutations = {
  SET_LIST: (state, list) => {
    state.list = shallowReactive(list);
  },
  SET_LISTTYPE: (state, list) => {
    state.type = list;
  },
  setIsDescendingOrder: (state, payload) => {
    state.isDescendingOrder = payload;
    state.list = shallowReactive(state.list.sort((a, b) => (!payload ? a.xuhao - b.xuhao : b.xuhao - a.xuhao)));
    setIsDescendingOrder(payload);
    sortSgbList(payload);
  },
};
const actions = {
  setList: async ({ commit }) => {
    const res = await getSgbItem(1000, 1, false, commit);
    commit("SET_LIST", res.data);
    return Promise.resolve(res.data);
  },
  getzaimeiType: async ({ commit }) => {
    if (state.type.length === 0) {
      const res = await getShiJiType();
      const { data } = res;
      commit("SET_LISTTYPE", data);
    }
    return state.type;
  },
  zmTypeCom: async ({ commit }, id) => {
    if (state.type.length === 0) {
      const res = await getShiJiType();
      const { data } = res;
      commit("SET_LISTTYPE", data);
    }
    return state.type.filter((item) => item.index === id)[0].shiJiName;
  },
  // 获取分页列表
  getList: async ({ state, dispatch }, loadplay) => {
    const { page, limit, index } = loadplay;
    const resultFun = () => {
      const list = state.list.filter((i) => i.shijiIndex == index);
      const total = list.length;
      const res = list.splice((page - 1) * limit, limit);
      return {
        list: res,
        total,
        shijiIndex: index,
        page,
      };
    };
    return new Promise((resolve) => {
      if (state.list.length === 0) {
        dispatch("setList").then(() => {
          resolve(resultFun());
        });
      } else {
        resolve(resultFun());
      }
    });
  },
  // 通过ID获取诗集信息
  getItem: async ({ state, commit }, id) =>
    new Promise((resolve) => {
      if (state.list.length === 0) {
        getSgbItem(1000, 1, false, commit)
          .then((res) => {
            commit("SET_LIST", res.data);
            const data = state.list.filter((i) => i._id === id);
            resolve(data[0]);
          })
          .catch((error) => {
            console.log("error-->", error);
          });
      } else {
        const data = state.list.filter((i) => i._id === id);
        resolve(data[0]);
      }
    }),
  // 通过ID获取诗集的上一曲和下一曲
  getNextPrev: ({ dispatch }, playload) => {
    const { index } = playload; // 诗集的index
    const { _id } = playload; // 当前诗集的ID
    return new Promise((resolve) => {
      dispatch("getList", { limit: 1000, page: 1, index }).then((res) => {
        const { list, total } = res;
        const arrIndex = list.findIndex((i) => i._id === _id);
        if (arrIndex === 0) {
          resolve({ next: list[1], prve: list[total - 1] });
          return;
        }
        if (arrIndex === total - 1) {
          resolve({ next: list[0], prve: list[arrIndex - 1] });
          return;
        }
        resolve({ next: list[arrIndex + 1], prve: list[arrIndex - 1] });
      });
    });
  },
  // 随机获取一首赞美的信息
  getRandome: ({ state, dispatch }, index) =>
    new Promise((resolve) => {
      dispatch("getList", { limit: 1000, page: 1, index }).then((res) => {
        const { list } = res;
        const newList = list.filter((i) => i.isad);
        const randomItem = (items) => items[(Math.random() * items.length) | 0];
        resolve(randomItem(newList));
      });
    }),
  // 获取所有的赞美列表
  getAllLIst: ({ state, dispatch }) =>
    new Promise(async (resolve) => {
      if (state.list.length === 0) {
        await dispatch("setList");
        resolve(state.list);
      } else {
        resolve(state.list);
      }
    }),
  // 通过多个id获致歌曲信息列表
  getItems: ({ state, dispatch }, ids) =>
    new Promise(async (resolve) => {
      if (state.list.length === 0) {
        await dispatch("setList");
      }
      console.log("ids-->", ids);
      const storeList = ids
        .map((id) => {
          const [cid, type = "0"] = id.split("|");

          if (parseInt(type) === GEDAN_LIST_TYPE.song) {
            const res = state.list.find((item) => item._id === cid);
            return {
              ...res,
              type: GEDAN_LIST_TYPE.song,
            };
          } else if (parseInt(type) === GEDAN_LIST_TYPE.jw) {
            return {
              _id: cid,
              mulu: cid,
              type: GEDAN_LIST_TYPE.jw,
              shijiName: "经文",
            };
          }
        })
        .filter((item) => item?._id);
      resolve(storeList);
    }),

  /**
   * 通过类型获取歌单列表
   * @param state
   * @param dispatch
   * @param option type可选值 shiji 和 gedan 当type为shiji时 id为0  0 是歌单的id
   * @returns {Promise<unknown>}
   */
  getGeDanList: ({ dispatch }, option = { type: "shiji", id: 0, uid: null }) => {
    const { type, id, uid } = option;
    return new Promise((resolve) => {
      switch (type) {
        case "shiji": // 诗集类型列表
          dispatch("getList", {
            page: 1,
            limit: 1000,
            index: id,
          }).then((res) => {
            resolve(res);
          });
          break;
        case "gedan": // 歌单类型列表
          gedanController.getGeDanDatailList(id).then((res) => {
            console.log(res);
            const ids = res.list;
            dispatch("getItems", ids).then((list) => {
              resolve({
                list: list.filter((item) => item.type == GEDAN_LIST_TYPE.song),
              });
            });
          });
          break;
        case "share": // 分享歌单类型列表
          gedanController.getGeDanDatailList(id, uid).then((res) => {
            const ids = res.list;
            dispatch("getItems", ids).then((list) => {
              resolve({
                list: list.filter((item) => item.type == GEDAN_LIST_TYPE.song),
              });
            });
          });
          break;
      }
    });
  },

  /**
   * 获取诗集类型
   */
  getNavJiList: ({ state }) =>
    new Promise((resolve) => {
      if (state.navList.length > 0) {
        resolve(state.navList);
        return;
      }
      getShiJiList()
        .then((res) => {
          state.navList = res.rows;
          resolve(state.navList);
        })
        .catch((error) => {
          console.log("获取列表失败");
          console.log(error);
          state.navList = [
            {
              id: 0,
              name: "赞美耶稣诗集(附录)",
              isUpper: 1,
              thumbnails: "https://lsky.top237.top/thumbnails/30ed39c29802b81fa4eceebc71fe1c84.png",
            },
            {
              id: 1,
              name: "赞美耶稣诗集",
              isUpper: 1,
              thumbnails: "https://lsky.top237.top/thumbnails/dabd6af9a64a77ba931ec42d8d3e8f07.png",
            },
            {
              id: 2,
              name: "新编赞美诗",
              isUpper: 1,
              thumbnails: "https://lsky.top237.top/thumbnails/5410f25f917765cb48e38c20d04350b4.png",
            },
            {
              id: 3,
              name: "少儿赞美",
              isUpper: 1,
              thumbnails: "https://lsky.top237.top/thumbnails/2c941411cdfe9f1ade7b99e5356791b6.png",
            },
            {
              id: 4,
              name: "默想音乐",
              isUpper: 1,
              thumbnails: "https://lsky.top237.top/thumbnails/d75c9c311902aea728b7a41a764b9004.png",
            },
            {
              id: 6,
              name: "圣诞主题赞美",
              isUpper: 1,
              thumbnails: "https://lsky.top237.top/thumbnails/2d35beabfae3a2b73a6f00efe6b03975.png",
            },
            {
              id: 7,
              name: "经文歌",
              isUpper: 1,
              thumbnails: "https://lsky.top237.top/thumbnails/61d57bbffc55f5438497ef16066a8c48.png",
            },
            {
              id: 8,
              name: "礼拜专用",
              isUpper: 1,
              thumbnails: null,
            },
          ];
          resolve(state.navList);
        });
    }),
  /**
   * 获取全部诗集类型列表
   * @param {*} param0
   * @returns
   */
  getAllShiJiList: ({ state }) =>
    new Promise((resolve) => {
      if (state.allSgbDbList.length > 0) {
        resolve(state.allSgbDbList);
        return;
      }
      getAllShiJiList()
        .then((res) => {
          state.allSgbDbList = res.rows;
          resolve(state.allSgbDbList);
        })
        .catch(() => {
          state.allSgbDbList = [
            {
              id: 8,
              name: "LB专用",
              isUpper: 1,
              thumbnails: null,
              starOrder: 0,
              type: "sgb_type",
              ids: null,
            },
            {
              id: 0,
              name: "赞美耶稣诗集(附录)",
              isUpper: 1,
              thumbnails: "",
              starOrder: 2,
              type: "sgb_type",
              ids: null,
            },
            {
              id: 1,
              name: "赞美耶稣诗集",
              isUpper: 1,
              thumbnails: "",
              starOrder: 3,
              type: "sgb_type",
              ids: null,
            },
            {
              id: 2,
              name: "新编赞美诗",
              isUpper: 1,
              thumbnails: "",
              starOrder: 4,
              type: "sgb_type",
              ids: null,
            },
            {
              id: 3,
              name: "少儿赞美",
              isUpper: 1,
              thumbnails: "",
              starOrder: 5,
              type: "sgb_type",
              ids: null,
            },
            {
              id: 4,
              name: "默想音乐",
              isUpper: 1,
              thumbnails: "",
              starOrder: 6,
              type: "sgb_type",
              ids: null,
            },
            {
              id: 6,
              name: "圣诞主题赞美",
              isUpper: 1,
              thumbnails: "https://project-star.oss-cn-beijing.aliyuncs.com/img/PixPin_2024-10-05_23-12-59.png",
              starOrder: 7,
              type: "original_type",
              ids: null,
            },
            {
              id: 7,
              name: "经文歌",
              isUpper: 1,
              thumbnails: "https://project-star.oss-cn-beijing.aliyuncs.com/img/PixPin_2024-10-05_23-15-39.png",
              starOrder: 8,
              type: "original_type",
              ids: null,
            },
            {
              id: 10,
              name: "Awesome",
              isUpper: 1,
              thumbnails: "https://project-star.oss-cn-beijing.aliyuncs.com/img/zheng_bang.png",
              starOrder: 9,
              type: "original_type",
              ids: null,
            },
            {
              id: 11,
              name: "David",
              isUpper: 1,
              thumbnails: "https://project-star.oss-cn-beijing.aliyuncs.com/img/da_wei.png",
              starOrder: 10,
              type: "original_type",
              ids: null,
            },
            {
              id: 12,
              name: "光的生活",
              isUpper: 1,
              thumbnails: "https://project-star.oss-cn-beijing.aliyuncs.com/img/769159f2276a41298ab0f9ab81dbb339.jpg",
              starOrder: 11,
              type: "original_type",
              ids: null,
            },
            {
              id: 13,
              name: "与神连接",
              isUpper: 1,
              thumbnails: "https://project-star.oss-cn-beijing.aliyuncs.com/img/20241023220750.jpg",
              starOrder: 12,
              type: "original_type",
              ids: null,
            },
          ];
          resolve(state.allSgbDbList);
        });
    }),
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
